﻿using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using SixLabors.ImageSharp.Drawing;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using UtilsBase;
using UtilsORM;
using UtilsORM.FileServerData;
using UtilsORM.MySqlData;

////using System.Web.Script.Serialization;

namespace ServiceWeb.WebAdmin
{
    public class ServiceFile
    {
        /// <summary>
        /// 新增文件或目录
        /// </summary>
        /// <param name="fileInfo"></param>
        /// <param name="parentGuid"></param>
        public void add(f_file fileInfo, string parentGuid)
        {

            EFYihongFileServerContext efYihongFileServerContext = new EFYihongFileServerContext();

            //判断是否有重复文件名
            f_file getFileOne = efYihongFileServerContext.f_file.Where(c => c.parent_guid == parentGuid).Where(c => c.name == fileInfo.name).FirstOrDefault();
            if (getFileOne != null)
            {
                //更新文件信息
                getFileOne.size = fileInfo.size;
                getFileOne.update_time = fileInfo.update_time;
                efYihongFileServerContext.SaveChanges();
                return;
            }

            //新增文件信息
            if (fileInfo.parent_guid == null || fileInfo.parent_guid == fileInfo.guid)
            {
                fileInfo.parent_guid = fileInfo.guid;
                fileInfo.parent_id = 0;
                fileInfo.level = 1;
            }
            else
            {
                f_file getFile = efYihongFileServerContext.f_file.Where(c => c.guid == fileInfo.parent_guid).FirstOrDefault();
                fileInfo.parent_id = getFile.id;
                fileInfo.level = getFile.level + 1;
            }


            efYihongFileServerContext.f_file.Add(fileInfo);
            efYihongFileServerContext.SaveChanges();
        }
       
        /// <summary>
        /// 获取文件列表
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="name"></param>
        /// <param name="parentGuid"></param>
        /// <param name="spaceType"></param>
        /// <returns></returns>
        public List<f_file> getList(int user_id, string name, string parentGuid, int spaceType)
        {
            EFYihongFileServerContext efYihongFileServerContext = new EFYihongFileServerContext();
            var efsql = efYihongFileServerContext.f_file.Where(p => p.status == 0 && p.space_type == spaceType);
            if (!string.IsNullOrEmpty(parentGuid))
            {
                efsql = efsql.Where(p => p.parent_guid == parentGuid && p.parent_guid != p.guid);
            }
            else
            {
                efsql = efsql.Where(p => p.parent_id == 0);
            }
            if (!string.IsNullOrEmpty(name))
            {
                efsql = efsql.Where(p => p.name.Contains(name));
            }
            if (spaceType == 0)
            {
                efsql = efsql.Where(p => p.user_id == user_id);
            }

            List<f_file> list = efsql.OrderBy(p => p.type).ThenBy(p => p.name).ThenBy(p => p.create_time).ToList();
            return list;
        }
        /// <summary>
        /// 获取文件信息
        /// </summary>
        /// <param name="Guid"></param>
        /// <returns></returns>
        public f_file getFileModel(string Guid)
        {
            EFYihongFileServerContext efYihongFileServerContext = new EFYihongFileServerContext();
            return efYihongFileServerContext.f_file.Where(c => c.guid == Guid && c.status == 0).FirstOrDefault();
        }

        /// <summary>
        /// 更新删除状态
        /// </summary>
        /// <param name="Guid"></param>
        public void updateDel(string dirpath, string Guid)
        {


            EFYihongFileServerContext efYihongFileServerContext = new EFYihongFileServerContext();
            efYihongFileServerContext.f_file.Where(c => c.guid == Guid && c.status == 0).ExecuteUpdate(c => c.SetProperty(p => p.status, 1)
                .SetProperty(p => p.del_time, DateTime.Now)
                .SetProperty(p => p.del_code, Guid)
            );
            efYihongFileServerContext.SaveChanges();


            int delcount = 0;//防止死循环
            List<string> dellist = new List<string>();
            dellist.Add(Guid);
            //循环删除子目录
            while (true)
            {

                dellist = updateDelStatus(dellist, Guid);
                if (dellist.Count == 0 || delcount > 50)
                {
                    break;
                }
                delcount = delcount + 1;
            }

            //删除文件
            List<f_file> files = efYihongFileServerContext.f_file.Where(c => c.status == 1 && c.type == "file" && c.del_code == Guid).ToList();
            foreach (f_file item in files)
            {
                string filePath = (dirpath + item.path + "/" + item.name).Replace("//", "/").Replace("\\", "/");
                if (System.IO.File.Exists(filePath))
                {
                    System.IO.File.Delete(filePath);

                }
                efYihongFileServerContext.f_file.Where(c => c.id == item.id).ExecuteDelete();
                efYihongFileServerContext.SaveChanges();
            }

            //删除文件夹,是先删除文件，才能删除文件夹
            files = efYihongFileServerContext.f_file.Where(c => c.status == 1 && c.type == "dir" && c.del_code == Guid).ToList();
            foreach (f_file item in files)
            {
                string filePath = (dirpath + item.path + "/" + item.name).Replace("//", "/").Replace("\\", "/");
                // 确保文件夹存在
                if (Directory.Exists(filePath))
                {
                    Directory.Delete(filePath);
                }
                efYihongFileServerContext.f_file.Where(c => c.id == item.id).ExecuteDelete();
                efYihongFileServerContext.SaveChanges();

            }
        }

        /// <summary>
        /// 更新删除状态,小心死循环
        /// </summary>
        /// <param name="dellist"></param>
        /// <returns></returns>
        public List<string> updateDelStatus(List<string> dellist, string delcode)
        {
            List<string> newdellist = new List<string>();
            EFYihongFileServerContext efYihongFileServerContext = new EFYihongFileServerContext();
            foreach (string item in dellist)
            {
                efYihongFileServerContext.f_file.Where(c => c.parent_guid == item && c.parent_id != 0 && c.status == 0).ExecuteUpdate(c => c.SetProperty(p => p.status, 1)
                    .SetProperty(p => p.del_time, DateTime.Now)
                    .SetProperty(p => p.del_code, delcode)
                );
                efYihongFileServerContext.SaveChanges();

                List<f_file> files = efYihongFileServerContext.f_file.Where(c => c.parent_guid == item && c.parent_id != 0 && c.del_code == delcode).ToList();
                foreach (f_file itemfile in files)
                {
                    newdellist.Add(itemfile.guid);
                }
            }
            return newdellist;
        }
        /// <summary>
        /// 获取目录路径
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public string getDirByGuid(string guid)
        {
            string dir = "/";

            EFYihongFileServerContext efYihongFileServerContext = new EFYihongFileServerContext();

            f_file dirmodel = getDirChildByGuid(guid);
            if (dirmodel == null)
            {
                return dir;
            }
            dir = dirmodel.name;
            while (true)
            {
                if (dirmodel.parent_id != 0 && dirmodel.parent_id != null && dirmodel.parent_id != dirmodel.id)
                {
                    dirmodel = getDirChildByGuid(dirmodel.parent_guid);
                    dir = "/" + dirmodel.name + "/" + dir;
                    dir = dir.Replace("//", "/");
                }
                else
                {
                    break;
                }
            }
            dir = dir.Replace("//", "/");
            return dir;
        }
        /// <summary>
        /// 获取目录下子目录
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public f_file getDirChildByGuid(string guid)
        {
            EFYihongFileServerContext efYihongFileServerContext = new EFYihongFileServerContext();
            return efYihongFileServerContext.f_file.Where(c => c.guid == guid && c.status == 0).FirstOrDefault();
        }
        /// <summary>
        /// 获取用户总空间大小
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public string getDirSumSpaceSize(int userId)
        {
            EFYihongFileServerContext efYihongFileServerContext = new EFYihongFileServerContext();
            double size = (double)efYihongFileServerContext.f_file.Where(c => c.user_id == userId && c.space_type == 0).Sum(c => c.size);
            return (size / 1024.0 / 1024.0).ToString("0.00");
        }
        /// <summary>
        /// 获取用户总文件数量
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public int getFileCount(int userId)
        {
            EFYihongFileServerContext efYihongFileServerContext = new EFYihongFileServerContext();
            return efYihongFileServerContext.f_file.Where(c => c.user_id == userId && c.space_type == 0).Count();

        }
    }

}
